<?php
/*=============================================================================
|| ##################################################################
||	phpFoX Konsort
|| ##################################################################
||	
||	Copyright		: (C) 2005-2007 PHPFOX Limited a Reality Fox Creation
||	Contact			: info@phpfox.com
||
||	- phpFoX and all of its source code and files are protected by Copyright Laws. 
||
||	- The license for phpFoX permits you to install this software on a single domain (.com, .org, .net, etc.). 
||
||	- You may also not remove this copyright screen which shows the copyright information and credits for phpFoX (RealityFOX Creations). 
||
||	- phpFoX Konsort is NOT a FREE software - http://www.phpfox.com/license/
||
|| ##################################################################
=============================================================================*/

/* $File: ./include/modules/Event/classes/PhpFox_ServiceEvent.class.php, $Author:  $ */



/** Service for working with events
 * 
 * @package module.event
 * @version $Id: PhpFox_ServiceEvent.class.php 422 2008-04-01 13:30:10Z phpfoxsv $
 *   
 */
class PhpFox_Mod_Event_ServiceEvent extends BaseService 
{
    function onDeleteAccount($aParams)
    {
        $oEventItem = $this->_oModule->getItem('Event');
        /* @var $oEventItem PhpFox_Mod_Event_ItemEvent */
        $oAccountService = &App::getModuleService('Account', 'Account');
        /* @var $oAccountService PhpFox_Mod_Account_ServiceAccount */

        $aIds = $aParams['aIds'];
        foreach ($aIds as $iUserId)
        {
            $oUser = $oAccountService->getById($iUserId);
            $sSql = 'SELECT id '.
                   ' FROM '.App::getT('events').' '.
                   ' WHERE user = "'.$oUser->aData['user'].'"';
            $aEvents = $oEventItem->oDb->getRows($sSql);
            foreach ($aEvents as $aEvent)
            {
                $this->deleteEvent($aEvent['id']);
            }
            $sSql = 'DELETE FROM '.App::getT('event_invite').' '.
                   ' WHERE user = "'.$oUser->aData['user'].'"';
            $oEventItem->oDb->query($sSql);
        }
    }

    /** Get events list
     * @param array $aCond
     * @param integer $iPage
     * @param integer $iPageSize
     * @param string $sSort
     * @return array
     */
    function getEventList($aCond = array(), $iPage = 0, $iPageSize = 0, $sSort = '')
    {
        $oEventItem = $this->_oModule->getItem('Event');
        /* @var $oEventItem PhpFox_Mod_Event_ItemEvent */

        $aMap = $oEventItem->aFields;
        $aFields = array();
        $sCond = $oEventItem->_parseCond($aCond, $aMap);

		$sSql = 'SELECT COUNT(*) '.
			' FROM `'.$oEventItem->sTable.'` AS '.$oEventItem->sAlias.
            ' WHERE e.private = 1 '.
            '   AND '.$sCond;
        $iCnt = $oEventItem->oDb->getField($sSql);
        $aRows = array();
        if ($iCnt)
        {
            $iOffset = $oEventItem->_getOffset($iPage, $iPageSize, $iCnt);
			$sSql = 'SELECT '.$oEventItem->_joinFields($aMap, $aFields).
                ' FROM `'.$oEventItem->sTable.'` AS '.$oEventItem->sAlias.
                ' WHERE e.private = 1 '.
                '   AND '.$sCond.
                ($sSort?(' ORDER BY '.$sSort):'').
            	($iPageSize?(' LIMIT '.$iOffset.','.$iPageSize):'');
            $aRows = $oEventItem->oDb->getRows($sSql);
            for ($i = 0; $i < count($aRows); $i++)
            {
                $aRows[$i]['start_date'] = strtotime($aRows[$i]['month'] . '/' . $aRows[$i]['day'] . '/' . $aRows[$i]['year']);
            }
        }
        return array($aRows, $iCnt);
    }

    /** Checks, that event with specified id can be shown for current user
     *
     * @param integer $iEventId
     * @return boolean
     */
    function isEventCanViewed($iEventId)
    {
    	return true;
        $oEventItem = $this->_oModule->getItem('Event');
        /* @var $oEventItem PhpFox_Mod_Event_ItemEvent */

        $iEventId = intval($iEventId);

        $sSql = 'SELECT COUNT(*) '.
                  ' FROM `'.$oEventItem->sTable.'` AS '.$oEventItem->sAlias.
                  ' WHERE e.private = 1 '.
                  '   AND e.id = '.$iEventId;

        return ($oEventItem->oDb->getField($sSql)) ? true : false;
    }

    /** Deleting event item
     * @param integer $iEventId Item Id
     * @return boolean
     */
    function deleteEvent($iEventId)
    {
        $oEventItem = $this->_oModule->getItem('Event');
        /* @var $oEventItem PhpFox_Mod_Event_ItemEvent */

        $iEventId = intval($iEventId);
        $oEventItem->delete($iEventId);
        $oEventItem->oDb->query('DELETE FROM '.App::getT('event_invite').' WHERE event_id = '.$iEventId);
        return true;
    }

    /** Get events invites
     * @param array $aCond
     * @param integer $iPage
     * @param integer $iPageSize
     * @param string $sSort
     * @param array $aFields
     * @return array
     */
    function getEventInvites($aCond = array(), $iPage = 0, $iPageSize = 0, $sSort = '', $aFields = array())
    {
        $oEventInviteItem = $this->_oModule->getItem('EventInvite');
        /* @var $oEventInviteItem PhpFox_Mod_Event_ItemEventInvite */
        $aMap = array
        (
        	'id'         => 'e.id',
        	'invite_id'  => 'ei.id',
        	'user'       => 'ei.user',
            'short'      => 'e.short',
        	'type'       => 'e.type',
        	'itype'      => 'ei.type',
            'city'       => 'e.city',
            'state'      => 'e.state',
            'country'    => 'e.country',
        	'invite'     => 'ei.invite',
        	'title'      => 'e.title',
        	'start_time' => 'e.start_time',
        	'year'       => 'e.year',
        	'month'      => 'e.month',
        	'day'        => 'e.day',
        );
        $sCond = $oEventInviteItem->_parseCond($aCond, $aMap);
        $sSql = 'SELECT COUNT(*) '.
               ' FROM `'.$oEventInviteItem->sTable.'` AS '.$oEventInviteItem->sAlias.
               ' LEFT JOIN '.App::getT('events').' AS e '.
               '        ON ei.event_id = e.id '.
               ' WHERE '.$sCond;
        $iCnt = $oEventInviteItem->oDb->getField($sSql);
        $aRows = array();
        if ($iCnt)
        {
            $iOffset = $oEventInviteItem->_getOffset($iPage, $iPageSize, $iCnt);
            $sSql = 'SELECT '.$oEventInviteItem->_joinFields($aMap, $aFields).
                   ' FROM `'.$oEventInviteItem->sTable.'` AS '.$oEventInviteItem->sAlias.
            	   ' LEFT JOIN '.App::getT('events').' AS e '.
            	   '        ON ei.event_id = e.id '.
                   ' WHERE '.$sCond.
                   ($sSort?(' ORDER BY '.$sSort):'').
                   ($iPageSize?(' LIMIT '.$iOffset.','.$iPageSize):'');
            $aRows = $oEventInviteItem->oDb->getRows($sSql);
        }
        return array($aRows, $iCnt);
    }

    /** Building calendar array
     * @param integer $iMonth month number
     * @param integer $iYear year
     * @return array
     */
    function buildCalendar($iMonth, $iYear)
    {
        $iFirstDayTimeStamp = mktime(0, 0, 0, $iMonth, 1, $iYear);
        $iFirstDayNum = date('w', $iFirstDayTimeStamp);
        $iFirstDayNum++;
        $iDayCount = date('t', $iFirstDayTimeStamp);
        $aCalendar = array();
        if ($iFirstDayNum > 1)
        {
            $aCalendar[1][''] = $iFirstDayNum - 1;
        }
        $i = 1;
        $j = 1;
        while ($j <= $iDayCount)
        {
            $aCalendar[$i][$j] = $j;
            if (floor(($j + $iFirstDayNum - 1) / 7) >= $i)
            {
                $i++;
            }
            $j++;
        }
        if ((isset($aCalendar[$i])) AND ($iM = count($aCalendar[$i])) < 7)
        {
            $aCalendar[$i][''] = 7 - $iM;
        }
        return $aCalendar;
    }

    /** Getting next month, year for any month
     * @param integer $iMonth month number
     * @param integer $iYear year
     * @return array [0] - month, [1] - year
     */
    function nextMonth($iMonth, $iYear)
    {
        if ($iMonth == 12)
        {
            $iMonth = 1;
            $iYear++;
        }
        else
        {
        	$iMonth++;
        }
        return array($iMonth, $iYear);
    }

    /** Returns timestamp for next day
     * @param integer $iDay day number
     * @param integer $iMonth month number
     * @param integer $iYear year
     * @return integer next day timestamp
     */
    function nextDay($iDay, $iMonth, $iYear)
    {
        $iDayTimestamp = mktime(0, 0, 0, $iMonth, $iDay, $iYear);
        $iNextDayTimestamp = strtotime('+1 day', $iDayTimestamp);
        return $iNextDayTimestamp;
    }

    /** Returns timestamp for previous day
     * @param integer $iDay day number
     * @param integer $iMonth month number
     * @param integer $iYear year
     * @return integer previous day timestamp
     */
    function prevDay($iDay, $iMonth, $iYear)
    {
        $iDayTimestamp = mktime(0, 0, 0, $iMonth, $iDay, $iYear);
        $iPrevDayTimestamp = strtotime('-1 day', $iDayTimestamp);
        return $iPrevDayTimestamp;
    }

    /** Getting previous month, year for any month
     * @param integer $iMonth month number
     * @param integer $iYear year
     * @return array [0] - month, [1] - year
     */
    function prevMonth($iMonth, $iYear)
    {
        if ($iMonth == 1)
        {
            $iMonth = 12;
            $iYear--;
        }
        else
        {
            $iMonth--;
        }
        return array($iMonth, $iYear);
    }

    /** Getting events array for any day number
     * @param integer $iDay day number
     * @param array $aEvents events array (events for needed month)
     * @param integer $iEventsMax max events counts (returns +1 count events)
     * @return array
     */
    function getDayEvents($iDay, $aEvents, $iEventsMax = 3)
    {
        $iEventsMax++;
        $aItems = array();
        if (strlen($iDay) == 1)
        {
            $iDay = '0'.$iDay;
        }
        $i = 0;
        foreach ($aEvents as $aEvent)
        {
            if ($aEvent['day'] == $iDay)
            {
                $i++;
                $aItems[] = $aEvent;
            }
            if ($iEventsMax == $i)
            {
                break;
            }
        }
        return !count($aItems) ? 0 : $aItems;
    }

    /** Get count of event invites for current user
     *
     * @return integer
     */
    function getInvitesCount()
    {
        $oEventInviteItem = $this->_oModule->getItem('EventInvite');
        /* @var $oEventInviteItem PhpFox_Mod_Event_ItemEventInvite */
        $oSecurityService = &App::getModuleService('Account', 'Security');
        /* @var $oSecurityService PhpFox_Mod_Account_ServiceSecurity */

        $sCurrentUser = $oSecurityService->getCurrentUserLogin();
        $sSql = 'SELECT COUNT(*) '.
               ' FROM '.App::getT('event_invite').' '.
               ' WHERE type = 0 '.
               '   AND invite = 0 '.
               '   AND user = "'.$sCurrentUser.'"';
        return $oEventInviteItem->oDb->getField($sSql);
    }
    
    function addComments($iEventId, $sText)
    {

    	//flood control
    	$iTime = time() - App::getSetting('flood_time');
		$checkCount = $this->oDatabase->getRow('SELECT time '.
			' FROM '.App::getT('event_invite').' '.
			' WHERE user = "'. App::getUser('user') .'" ORDER BY time DESC LIMIT 0,1');
		if ( isset($checkCount['time']) AND (($checkCount['time'] + App::getSetting('flood_time')) >= time()) )
		{
			$this->addErrors( App::format('Mod_Comments.flooded', App::getSetting('flood_time')) );
			return false;
		}

		$oSecurityService = &App::getModuleService('Account', 'Security');
        /* @var $oSecurityService PhpFox_Mod_Account_ServiceSecurity */
        $oBlockService = &App::getModuleService('Account', 'Block');
        /* @var $oBlockService PhpFox_Mod_Account_ServiceBlock */
    	$oEventItem = $this->_oModule->getItem('Event');
        /* @var $oEventItem PhpFox_Mod_Event_ItemEvent */
        $oEventInviteItem = $this->_oModule->getItem('EventInvite');
        /* @var $oEventInviteItem PhpFox_Mod_Event_ItemEventInvite */

        if(
        	(!$oSecurityService->checkAccess('events','',FALSE))
        	OR
        	(!$oSecurityService->checkPerm('events', array('full'), false))
        	OR
        	(!$iEventId)
        	OR
        	(!$this->isEventCanViewed($iEventId))
        	OR
        	(!$oEventItem->load($iEventId))
       	)
        {
            return FALSE;
        }
        
        $oOwner = $oSecurityService->getUserByName($oEventItem->aData['user']);
        $oUser = $oSecurityService->getCurrentUser();
       	if ($oBlockService->isBlocked($oOwner, $oUser))
        {
            $this->addErrors(App::format('Mod_Event.error.blocked'));
            return FALSE;
        }

        $oEventInviteItem->aData['user']     = $sUser = $oUser->aData['user'];
        $oEventInviteItem->aData['event_id'] = $iEventId;
        $oEventInviteItem->aData['text']     = $sText;
        $oEventInviteItem->aData['invite']   = 0;
        $oEventInviteItem->aData['time']     = time();
        $oEventInviteItem->aData['type']     = 1;
        $iRes = $oEventInviteItem->insert();
        
        if(!$iRes)
        {
        	$this->addErrors($oEventInviteItem->getErrors());
        	return FALSE;
        }
        if (($oUser->aData['user'] != $oOwner->aData['user']) && ($oOwner->aData['not_1'] != 0))
        {
            $oMailer = &App::newObject('mail_Mailer');
            /* @var $oMailer mail_Mailer */
            $sSubject = App::format('core.comment');
            $sTo = $oOwner->aData['email'];
            $aVars = array
            (
                'TO'           => $oOwner->aData['user'],
                'FROM'         => $sUser,
                'SITENAME'     => App::getParam('url'),
                'HOME'         => App::getParam('url'),
                'COMMENT_LINK' => App::makeUrl('public.event.view', array('id' => $iEventId)),
            );
            $oMailer->send('email_comment', $sTo, $sSubject, $aVars);
        }
        return $iRes;
    }
}
?>